import { useEffect, useState } from 'react';
import { Message, Input, Form, Box, Button, Card, DatePicker, Radio, Upload, Table, Rating, List, Avatar } from '@alifd/next';
import type { UploadProps } from '@alifd/next/types/upload';
import { Moment } from 'moment';
import styles from './index.module.css';
import EditableCell from './EditableCell';
import { RadioGroup } from '@alifd/next/types/radio/radio-group';
import ChooseFeel from './ChooseFeel';
import ChooseTimeLine from './ChooseTimeLine';
import reminds from './reminds';

const FormItem = Form.Item;

const formItemLayout = {
  colSpan: 12,
};

export interface DataSource {
  name?: string;
  category?: string;
  date?: Moment[];
  type?: string;
  pic?: UploadProps[];
  desc?: string;
}

export interface BasicFormProps {
  humanList: any;
  iwant: any;
  robotList: any;
  onChange?: () => void;
}

const DEFAULT_DATA: DataSource = {
  type: 'private',
};
function pailie(list, prePrefix?) {
  let prefix = prePrefix || [];
  let result = [];
  for (let i = 0; i < list.length; i++) {
    let temp = [...prefix, list[i]]
    result = result.concat(pailie(list.slice(i + 1), temp));
    result.push(temp);
  }
  if (!prePrefix) {
    return result.filter((item: any) => {
      return item.length > 1;
    }).sort((item1, item2) => {
      return item1.length > item2.length ? 1 : -1;
    });
  } else {
    return result;
  }
}
const DEFAULT_ON_SUBMIT = (values: BasicFormProps, errors: []): void => {
  if (errors) {
    console.log('errors', errors);
    return;
  }
  console.log('values:', values);
  Message.success('提交成功');
};
function createDefaultValue() {
  return {
    feel: 0,
    score: 0,
    detail: '',
    daju: '',
    fanxiang: '',
    timeRange: null
  }
}
export const ChooseTable: React.FC<BasicFormProps> = (props: {
  title: string
  iwant: any
  robotList: any
  humanList: any
}): JSX.Element => {
  const [robotList, setRobotList] = useState(props.robotList || []);
  const [dataSource, setDataSource] = useState(props.humanList || []);
  const [iwant, setIwant] = useState(props.iwant || '');
  const propsConf = {
    className: 'next-myclass',
    style: { background: 'rgba(0,0,0,0.02)' },
    onDoubleClick: () => {
      console.log('doubleClicked');
    },
  };
  const choosePropsConf = {
    className: 'next-choose',
    style: { background: 'black', color: 'white' },
    onDoubleClick: () => {
      console.log('doubleClicked');
    },
  };
  const setRowProps = (record, index) => {
    if (record.type === 'robot') {
      return propsConf;
    }
  };
  const setCellProps = (rowIndex, colIndex, dataIndex, record) => {

  };
  // const getRobotList = (datas) => {
  //   const humans = datas.filter(item => {
  //     return item.type == 'human';
  //   });
  //   let humanIds = humans.map(item => {
  //     return item.id;
  //   }).sort();

  //   let robotChooses = pailie(humanIds);
  //   let alreadyRobotMaps = {};
  //   robotList.forEach(element => {
  //     alreadyRobotMaps[element.id] = element;
  //   });
  //   let alreadyMaps = {};
  //   datas.forEach(element => {
  //     alreadyMaps[element.id] = element;
  //   });
  //   // 自动生成决策
  //   let zidongs = robotChooses.map((itemIds: any) => {
  //     let itemId = itemIds.join('_');
  //     let oldData = alreadyRobotMaps[itemId] ? alreadyRobotMaps[itemId] : {};
  //     const { choose, ...attrValue } = oldData;
  //     return {
  //       choose: '同时 ' + itemIds.map(chooseId => {
  //         return alreadyMaps[chooseId].choose
  //       }).join(' 和 '),
  //       ...createDefaultValue(),
  //       type: 'robot',
  //       id: itemId,
  //       ...(attrValue ? attrValue : {})
  //     }
  //   });
  //   return zidongs;
  // }
  useEffect(() => {
    // setRobotList(getRobotList(dataSource));
  }, [dataSource, iwant]);
  useEffect(() => {
    props.onChange && props.onChange({
      robotList,
      humanList: dataSource,
      iwant: iwant
    });
  }, [dataSource, iwant]);
  const changeValue = (record, index, key, value) => {
    if (record.type == 'human') {
      dataSource[index] = {
        ...dataSource[index],
        [key]: value
      }
      setDataSource([
        ...dataSource
      ]);
    } else {
      let robotIndex = index - dataSource.length;
      robotList[robotIndex] = {
        ...robotList[robotIndex],
        [key]: value
      }
      setRobotList([
        ...robotList
      ]);
    }
  }

  const [remindIndex, setRemindIndex] = useState(0);
  useEffect(() => {
    if (reminds[props.title]) {
      let timer = setInterval(() => {
        setRemindIndex(Math.floor(Math.random() * reminds[props.title].length));
      }, 5000);
      return () => {
        clearInterval(timer);
      }
    }
  }, []);
  return (
    <Card free>
      <Card.Content>
        <div style={{
        }}>
          <Card free>
            <div style={{
              display: 'flex'
            }}>你必须为了这个目标每天都在不断地努力
              {reminds[props.title] && <div>
                --------------{reminds[props.title][remindIndex]}
              </div>}
            </div>
            <Input.TextArea autoHeight={{
              minRows: 2,
              maxRows: 10
            }} value={iwant} onChange={(value) => {
              setIwant(value);
            }} placeholder='战略第一，战略就是冥想' style={{
              width: '100%'
            }}></Input.TextArea>
          </Card>

          <Table
            key={"id"}
            // expandedRowIndent={[1,1]}
            expandedIndexSimulate={true}
            expandedRowRender={(record, index) => {
              return <div style={{
                display: 'flex'
              }}>
                <Input.TextArea style={{
                  width: '100%'
                }} defaultValue={record.detail} onBlur={(e) => {
                  let value = e.target.value;
                  changeValue(record, index, 'detail', value);
                }}></Input.TextArea>
                <br /><br />
                <ChooseTimeLine value={record.timeRange} onChange={(value) => {
                  changeValue(record, index, 'timeRange', value);
                }}></ChooseTimeLine>
              </div>
            }}
            dataSource={[...dataSource]} rowProps={setRowProps} cellProps={setCellProps}>
            <Table.Column style={{
              width: '500px'
            }} title={() => {
              return <div>

                <div>
                  生活的目的-行动起来(不对任何的坏事做出反应，死也认了)<br />珍惜这操蛋的当下, 去预测那遥不可及的未来
                  <Button onClick={() => {
                    let list = [
                      ...dataSource,
                      {
                        choose: '选择',
                        ...createDefaultValue(),
                        type: 'human',
                        id: new Date().getTime()
                      },
                    ];
                    setDataSource(list);
                  }}>追加</Button>
                  <Button onClick={() => {
                    let list = [
                      {
                        choose: '选择',
                        ...createDefaultValue(),
                        type: 'human',
                        id: new Date().getTime()
                      },
                      ...dataSource,
                    ];
                    setDataSource(list);
                  }}>前加</Button>
                </div>
              </div>
            }} dataIndex="choose" cell={(value, index, record) => {
              if (record.type == 'human') {
                return <Input.TextArea style={{
                  width: '100%'
                }} autoHeight={{
                  minRows: 2,
                  maxRows: 10
                }} value={value} onChange={(value) => {
                  dataSource[index] = {
                    ...dataSource[index],
                    choose: value
                  }
                  setDataSource([
                    ...dataSource
                  ]);
                }} onBlur={(e) => {
                  let value = e.target.value;
                  if (value.trim() == '') {
                    dataSource.splice(index, 1);
                    setDataSource([
                      ...dataSource
                    ]);
                  }
                }} />;
              } else {
                return value;
              }
            }} />
            <Table.Column style={{
              width: '400px'
            }} title={<div>
              {/* <Input value={iwant} onChange={(value) => {
                setIwant(value);
              }} placeholder='三方想做，注意成功的关键在于不考虑正确和利益，因为成功的标准就是自己满意' style={{
                width: '100%'
              }} /> */}
              当下的能接受（能接受即可，不求更好，亏也认了，别把自己逼到要止损的哪一步）<br />
              当下有没有你能接受的止盈的感觉
            </div>} dataIndex="dangxia_nengjieshou" cell={(value, index, record) => {
              // return <ChooseFeel value={value} onChange={(value) => {
              //   changeValue(record, index, 'feel', value);
              // }}></ChooseFeel>
              return <Input.TextArea style={{
                width: '100%'
              }} autoHeight={{
                minRows: 2,
                maxRows: 10
              }} value={value} onChange={(value) => {
                changeValue(record, index, 'dangxia_nengjieshou', value);
              }} />
            }} />
            <Table.Column style={{
              width: '400px'
            }} title={
              <div>
                想想未来的参考点(从不可能得角度去想)<br />你觉得OK的止损，止盈点事什么
              </div>
            } dataIndex="weilai_cankandian" cell={(value, index, record) => {
              // return <Input.TextArea autoHeight={{
              //   minRows: 2,
              //   maxRows: 10
              // }} style={{
              //   width: '100%'
              // }} value={value} onChange={(value) => {
              //   changeValue(record, index, 'fanxiang', value);
              // }} />
              return <Input.TextArea style={{
                width: '100%'
              }} autoHeight={{
                minRows: 2,
                maxRows: 10
              }} value={value} onChange={(value) => {
                changeValue(record, index, 'weilai_cankandian', value);
              }} />
            }} />
          </Table>
          {/* <div style={{
            flex: 1
          }}>
            <List
              size="small"
              style={{
                width: '100%',
                marginLeft: '5px'
              }}
              header={<div>注意事项</div>}
              dataSource={reminds[props.title] || []}
              renderItem={(item, i) => (
                <List.Item key={i} title={item} ></List.Item>
              )}
            />
          </div> */}
        </div>
      </Card.Content>
    </Card>
  );
};

export default ChooseTable;
